<template>
    <div class="validate-form-container">
        <form>
            <slot name="default"></slot>
            <div class="footer mt-4" @click.prevent="handleSubmit">
                <slot name="footer">
                    <button class="btn btn-primary w-100">提交</button>
                </slot>
            </div>
        </form>
    </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue';
import Mitt from 'mitt';

export const mitter = Mitt();

type ValidateFunctionType = () => boolean;

const validatorFuncArr: ValidateFunctionType[] = [];

export default defineComponent({
    emits: ['form-submit'],
    // beforeCreate、created
    setup(props, ctx) {
        const handleSubmit = () => {
            // 循环执行这些校验函数
            const isOk = validatorFuncArr
                .map(func => func())
                .every(isOk => isOk);
            // 触发表单提交
            ctx.emit('form-submit', isOk);
        };

        // 监听子组件的创建
        mitter.on('form-item-created', (func?: ValidateFunctionType) => {
            if (func && typeof func === 'function') {
                validatorFuncArr.push(func);
            }
        });

        return { handleSubmit };
    }
});
</script>
